package org.lib.dbpoolhello.country.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.lib.dbpoolhello.country.dao.CountryDAO;
import org.lib.dbpoolhello.country.dto.AddCountryDTO;
import org.lib.dbpoolhello.country.entity.Country;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * 国家Api
 * @author ben
 * @date 2021-09-28 17:57:16 CST
 */
@RestController
@RequestMapping(value="/api/country")
@Slf4j
public class CountryApi {

	@Autowired
	private CountryDAO countryDao;
	
	@Autowired
	private HttpServletResponse resp;
	
	/**
	 * 添加国家
	 * @author ben
	 * @date 2021-09-28 18:04:25 CST
	 * @param dto
	 * @return
	 */
	@PostMapping(value="/add")
	public Long add(@RequestBody @Validated AddCountryDTO dto, BindingResult bresult) {
		if (bresult.hasErrors()) {
			try {
				String msg1 = bresult.getAllErrors().get(0).getDefaultMessage();
				resp.sendError(HttpStatus.BAD_REQUEST.value(), msg1);
			} catch (IOException e) {
				log.error("sendError发生异常：e={}", e.getMessage());
			}
			return null;
		}
		
		Country cnt = new Country();
		
		BeanUtils.copyProperties(dto, cnt);
		
		countryDao.save(cnt);
		
		Long id = cnt.getId();
		if (id != null) {
			log.info("添加国家：成功，id={}", id);
			return id;
		} else {
			log.error("添加国家：失败，dto={}", dto);
			return null;
		}
	}
	
	/**
	 * 查找：根据ID
	 * @author ben
	 * @date 2021-09-28 18:04:32 CST
	 * @param id
	 * @return
	 */
	@GetMapping(value="/getById")
	public Country getById(@RequestParam Long id) {
		if (id == null || id < 1) {
			try {
				resp.sendError(HttpStatus.BAD_REQUEST.value(), "id错误");
			} catch (IOException e) {
				log.error("sendError发生异常：e={}", e.getMessage());
			}
			return null;
		}
		
		return countryDao.findById(id).orElse(null);
	}
	
}
